package com.cn.lp.export.server.entity.executor;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.cn.lp.export.server.base.context.CoreResponseCode;
import com.cn.lp.export.server.base.context.ExportExceptionCreator;
import com.cn.lp.export.server.controller.CreateExportTaskRequest;
import com.cn.lp.export.server.entity.ExportTask;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

/**
 * 本地文件系统导出
 *
 * @author wuqirong
 * @date 2020-10-21
 * <p>
 * All rights Reserved, Designed www.xiao100.com
 */
public class LocalFileSystemExportExecutor extends BaseExportExecutor {

    @Override
    protected void doExport(ExportTask exportTask, List<List<Object>> excelExportDataList, List<List<String>> excelHeaderList) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ExcelWriter writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0);
        sheet.setSheetName("Sheet1");
        sheet.setHead(excelHeaderList);
        writer.write1(excelExportDataList, sheet);
        writer.finish();
        Path path = Paths.get(exportTask.getResultUrl());
        File file = path.getParent().toFile();
        if(!file.exists()) {
            file.mkdirs();
        }
        try {
            Files.write(path, outputStream.toByteArray());
        } catch (IOException e) {
            throw ExportExceptionCreator.create(CoreResponseCode.UNKNOWN_ERROR.getCode(), exportTask.getExcelName() + "导出失败", e);
        }
    }

    @Override
    public ExportResult createResultUrl(CreateExportTaskRequest createRequest) {
        String excelName = createRequest.getExcelName() + "_" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + ".xlsx";
        String resultUrl = "D:\\export\\" + excelName;
        return ExportResult.of(excelName, resultUrl);
    }
}
